package com.haiheng.voiceandbook


import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.SCALEIN
import com.haiheng.bookmusic.base.BaseActivity
import com.haiheng.bookmusic.common.CategoryBean
import com.haiheng.bookmusic.common.TagBean
import com.haiheng.voiceandbook.adapter.*
import com.haiheng.voiceandbook.common.BookDto
import com.haiheng.voiceandbook.common.CategoriesDto
import com.haiheng.voiceandbook.common.SearchVo
import com.haiheng.voiceandbook.databinding.ActivityFindBinding
import com.haiheng.voiceandbook.utils.AppUtils
import com.haiheng.voiceandbook.utils.Density
import com.haiheng.voiceandbook.utils.DisplayUtil
import com.haiheng.voiceandbook.utils.SmartDialogUtils
import com.haiheng.voiceandbook.view.RecyclerViewSpacesItemDecoration
import com.haiheng.voiceandbook.voice.TracksActivity
import com.ximalaya.ting.android.opensdk.constants.DTransferConstants
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack
import com.ximalaya.ting.android.opensdk.model.album.Album
import com.ximalaya.ting.android.opensdk.model.album.AlbumList
import com.ximalaya.ting.android.opensdk.model.album.SearchAlbumList
import com.ximalaya.ting.android.opensdk.model.category.CategoryList
import com.ximalaya.ting.android.opensdk.model.tag.TagList
import kotlinx.coroutines.launch
import layout.AlbumAdapter


/**
 * 搜索
 */
class SearchActivity : BaseActivity() {

    var pageNo: Int = 1
    val pageSize: Int = 20
    var activityFindBinding: ActivityFindBinding? = null
    var type = 0
    var booksList = mutableListOf<BookDto>()
    override fun initDataChange() {
        bookViewModel!!.categories.observe(this, Observer {
//            val data = it.data?.data
            val data = it
            if (data != null && data.size > 0) {
                var categoriesList = mutableListOf<CategoriesDto>()
                categoriesList.addAll(data)
                categoriesList.get(0).isSelect = true
                var allTypeAdapter: AllTypeBookAdapter? =
                    AllTypeBookAdapter(R.layout.item_type_left, categoriesList)
                allTypeAdapter?.apply {
                    setOnItemClickListener { adapter, view, position ->
                        categoriesList?.forEach {
                            if (categoriesList.indexOf(it) == position) {
                                it.isSelect = true
                                pageNo = 1
                                booksByCategoryId(it.getCategoryId())
                            } else {
                                it.isSelect = false
                            }

                        }
                        allTypeAdapter?.notifyDataSetChanged()
                        activityFindBinding!!.rvLeft.scrollToPosition(position)
                    }
                }
                activityFindBinding!!.rvLeft.adapter = allTypeAdapter
                booksByCategoryId(categoriesList[0].getCategoryId())
            } else {
                Toast.makeText(this@SearchActivity, "获取分类异常", Toast.LENGTH_SHORT).show()
            }


        })
        bookViewModel!!.books.observe(this, Observer
        {
            hideLoadingDialog()
            activityFindBinding?.srHasData?.finishRefresh()
            activityFindBinding?.srHasData?.finishLoadMore()
            val data = it.data?.data?.books
            if (data != null && data.size > 0) {
                if (pageNo == 1) {
                    booksList.clear()
                }
                booksList.addAll(data)
                val bookAdapter = BookAdapter(R.layout.item_main_three, booksList)
                activityFindBinding?.rvRight!!?.adapter = bookAdapter
                bookAdapter?.apply {
                    openLoadAnimation(SCALEIN)//缩放
                    setOnItemClickListener { adapter, view, position ->
                        val item = adapter.getItem(position) as BookDto
                        getBooKDetail(item.getBookId())

                    }
                }
            } else {
                if (pageNo > 1) {
                    pageNo--
                }
            }


        })


    }

    /**
     * 获取书籍详情信息
     */
    private fun getBooKDetail(bookId: Long) {
        lifecycleScope.launch {
             if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                 showTipsDialog(getString(R.string.no_net_hint))
             }else{
                 showLoadingDialog()
                 val bookDetail = bookViewModel?.getBookDetail(bookId)
                 hideLoadingDialog()
                 showBookDetailDialog(bookDetail)
             }
        }

    }



    var mCategoryId: Long = 0
    var mCategoryName: String? = null
    private fun booksByCategoryId(categoryId: Long) {
        showLoadingDialog()
        mCategoryId = categoryId
        bookViewModel!!.booksByCategoryId(categoryId, pageNo, pageSize)
    }


    override fun initListener() {
        activityFindBinding?.ivMain?.setOnClickListener {
            finish()

        }
        activityFindBinding?.rlSearch?.setOnClickListener {
            if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                showTipsDialog(getString(R.string.no_net_hint))
            }else{
                showBookFindDialog()
            }

        }
        activityFindBinding?.llVoice?.setOnClickListener {
            type = 0
            getData()
        }
        activityFindBinding?.llBook?.setOnClickListener {
            type = 1
            getData()
        }
        activityFindBinding?.srHasData?.setOnRefreshListener {
            pageNo = 1
            if (type == 0) {
                if (TextUtils.isEmpty(categoryId)){
                    if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                        Toast.makeText(this,"网络异常",Toast.LENGTH_SHORT).show();
                    }
                    return@setOnRefreshListener
                }
                getAlbumList(categoryId!!, tagName!!)
            } else {
                booksByCategoryId(mCategoryId)
            }

        }

        activityFindBinding?.srHasData?.setOnLoadMoreListener {
            pageNo++
            if (type == 0) {
                getAlbumList(categoryId!!, tagName!!)
            } else {
                booksByCategoryId(mCategoryId)
            }

        }
    }

    /**
     * 搜索书
     */
    private fun showBookFindDialog() {
        Density.setDensity(getApplication(), this)
        var myType = type
        val dialog: Dialog =
            SmartDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_book_find)
        val iv_close = dialog.findViewById<ImageView>(R.id.iv_close) as ImageView
        val et_name = dialog.findViewById<EditText>(R.id.et_name) as EditText
        val recyclerView = dialog.findViewById<RecyclerView>(R.id.recyclerView) as RecyclerView
        val rl_nodata = dialog.findViewById<LinearLayout>(R.id.rl_nodata) as LinearLayout

        val tvVoice = dialog.findViewById<TextView>(R.id.tv_voice) as TextView
        val ivVoice = dialog.findViewById<ImageView>(R.id.iv_voice) as ImageView
        val tvBook = dialog.findViewById<TextView>(R.id.tv_book) as TextView
        val ivBook = dialog.findViewById<ImageView>(R.id.iv_book) as ImageView


        val llVoice = dialog.findViewById<LinearLayout>(R.id.ll_voice) as LinearLayout

        val llBook = dialog.findViewById<LinearLayout>(R.id.ll_book) as LinearLayout

        llVoice?.setOnClickListener {
            myType = 0
            tvVoice?.setTextColor(resources.getColor(R.color.color_red_E8))
            ivVoice?.visibility = View.VISIBLE
            tvBook?.setTextColor(resources.getColor(R.color.color_text))
            ivBook?.visibility = View.GONE

        }
        llBook?.setOnClickListener {
            myType = 1
            tvVoice?.setTextColor(resources.getColor(R.color.color_text))
            ivVoice?.visibility = View.GONE
            tvBook?.setTextColor(resources.getColor(R.color.color_red_E8))
            ivBook?.visibility = View.VISIBLE

        }

        if (myType == 0) {
            tvVoice?.setTextColor(resources.getColor(R.color.color_red_E8))
            ivVoice?.visibility = View.VISIBLE
            tvBook?.setTextColor(resources.getColor(R.color.color_text))
            ivBook?.visibility = View.GONE
        } else {

            tvVoice?.setTextColor(resources.getColor(R.color.color_text))
            ivVoice?.visibility = View.GONE
            tvBook?.setTextColor(resources.getColor(R.color.color_red_E8))
            ivBook?.visibility = View.VISIBLE
        }


        val stringIntegerHashMap =
            HashMap<String, Int>()
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.TOP_DECORATION] =
            DisplayUtil.dip2px(this, 7f)

        recyclerView.addItemDecoration(
            RecyclerViewSpacesItemDecoration(
                stringIntegerHashMap
            )
        )
        recyclerView.layoutManager = LinearLayoutManager(this)
        iv_close.setOnClickListener {
            dialog.dismiss()
        }
        et_name.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(et_name.text.toString())) {
                    return
                }
                if (myType == 0) {
                    val map = HashMap<String, String>()
                    map.put(DTransferConstants.SEARCH_KEY, et_name.text.toString())
                    map.put(DTransferConstants.PAGE_SIZE, "20")
                    CommonRequest.getSearchedAlbums(map, object : IDataCallBack<SearchAlbumList> {
                        override fun onSuccess(p0: SearchAlbumList?) {
                            val albumsList = p0?.albums
                            if (albumsList != null && albumsList.size > 0) {
                                val voiceFindAdapter =
                                    VoiceFindAdapter(R.layout.item_find_item, albumsList)
                                recyclerView?.adapter = voiceFindAdapter
                                voiceFindAdapter?.apply {
                                    openLoadAnimation(SCALEIN)//缩放
                                    setOnItemClickListener { adapter, view, position ->
                                        val item = adapter.getItem(position) as Album
                                        val intent =
                                            Intent(this@SearchActivity, TracksActivity::class.java)
                                        intent.putExtra("id", item.id.toString())
                                        val bundle = Bundle()
                                        bundle.putParcelable("album", item)
                                        intent.putExtra("bundle", bundle)
                                        startActivity(intent)
                                        dialog.dismiss()
                                    }

                                }
                                rl_nodata.visibility = View.GONE
                                recyclerView.visibility = View.VISIBLE


                            } else {
                                rl_nodata.visibility = View.VISIBLE
                                recyclerView.visibility = View.GONE
                            }

                        }

                        override fun onError(p0: Int, p1: String?) {
                            Toast.makeText(this@SearchActivity, "系统异常：${p1}", Toast.LENGTH_SHORT)
                                .show()
                            rl_nodata.visibility = View.VISIBLE
                            recyclerView.visibility = View.GONE
                        }

                    })

                } else {
                    val vo = SearchVo(et_name.text.toString(), 3, 1, 20)
                    lifecycleScope.launch {
//                        showLoadingDialog()
                        val list = bookViewModel!!.search(vo)
                        if (list != null && list.size > 0) {
                            rl_nodata.visibility = View.GONE
                            recyclerView.visibility = View.VISIBLE
                            val bookFindAdapter = BookFindAdapter(R.layout.item_find_item, list)
                            recyclerView?.adapter = bookFindAdapter
                            hideLoadingDialog()
                            bookFindAdapter?.apply {
                                openLoadAnimation(SCALEIN)//缩放
                                setOnItemClickListener { adapter, view, position ->
                                    val item = adapter.getItem(position) as BookDto
                                    getBooKDetail(item.getBookId())
                                    dialog.dismiss()
                                }

                            }
                        } else {
                            hideLoadingDialog()
                            rl_nodata.visibility = View.VISIBLE
                            recyclerView.visibility = View.GONE
                        }

                    }

                }


            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })


        dialog.show()

    }


    override fun initData() {
        //0 有声书
        //1 电子书
        type = intent.getIntExtra("type", 0)
        getData()

    }

    private fun getData() {
        pageNo = 1
        if (type == 0) {

            activityFindBinding?.run {
                rvTop?.visibility = View.VISIBLE
                tvVoice?.setTextColor(resources.getColor(R.color.color_red_E8))
                ivVoice?.visibility = View.VISIBLE
                tvBook?.setTextColor(resources.getColor(R.color.color_text))
                ivBook?.visibility = View.GONE
            }
            getCategories()
        } else {

            bookViewModel!!.categories()
            activityFindBinding?.run {
                rvTop?.visibility = View.GONE
                tvVoice?.setTextColor(resources.getColor(R.color.color_text))
                ivVoice?.visibility = View.GONE
                tvBook?.setTextColor(resources.getColor(R.color.color_red_E8))
                ivBook?.visibility = View.VISIBLE

            }


        }
    }


    override fun initView() {
        //第三个参数是用来控制滑动方向的

        activityFindBinding!!.rvLeft.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        val gridLayoutManager = GridLayoutManager(this, 3)
        activityFindBinding?.rvRight!!.layoutManager = gridLayoutManager

        val map = HashMap<String, Int>()
        map.put(
            RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION,
            DisplayUtil.dip2px(this, 10f)
        )
        val decoration = RecyclerViewSpacesItemDecoration(
            map
        )
        activityFindBinding?.rvRight?.addItemDecoration(
            decoration
        )


        //

        val mapTop = HashMap<String, Int>()
        mapTop.put(
            RecyclerViewSpacesItemDecoration.RIGHT_DECORATION,
            DisplayUtil.dip2px(this@SearchActivity, 10f)
        )
        val decorationTop = RecyclerViewSpacesItemDecoration(
            mapTop
        )
        activityFindBinding?.rvTop?.addItemDecoration(
            decorationTop
        )

    }

    override fun intiLayout() {
        activityFindBinding = ActivityFindBinding.inflate(LayoutInflater.from(this))
        setContentView(activityFindBinding?.getRoot())
    }

    val categoryList = mutableListOf<CategoryBean>()
    var categoryId: String? = null

    /**
     *  获取所有有声书的分类
     */
    private fun getCategories() {
        val map = HashMap<String, String>()
        CommonRequest.getCategories(map, object : IDataCallBack<CategoryList> {
            override fun onSuccess(ximalist: CategoryList?) {
                lifecycleScope.launch {
                    categoryList?.clear()
                    var list = bookViewModel?.filterXimaVoiceCategories(ximalist)
                    categoryId = list?.categories?.get(0)?.id.toString()
                    getTags(categoryId!!)
                    list?.categories?.forEach {
                        if (list?.categories.indexOf(it) == 0) {
                            val bean = CategoryBean(true, it)
                            categoryList?.add(bean)
                        } else {
                            val bean = CategoryBean(false, it)
                            categoryList?.add(bean)
                        }

                    }
                    val allTypeAdapter = AllTypeVoiceAdapter(R.layout.item_type_left, categoryList)
                    allTypeAdapter?.apply {
                        setOnItemClickListener { adapter, view, position ->
                            categoryList?.forEach {
                                if (categoryList.indexOf(it) == position) {
                                    it.isSelect = true
                                    categoryId = it?.category.id.toString()
                                    getTags(categoryId!!)
                                } else {
                                    it.isSelect = false
                                }

                            }
                            allTypeAdapter?.notifyDataSetChanged()
                            activityFindBinding?.rvLeft?.scrollToPosition(position)
                        }
                    }
                    activityFindBinding?.rvLeft?.adapter = allTypeAdapter
                }
            }

            override fun onError(p0: Int, p1: String?) {
                Log.e(TAG, "onError: ${p0} and ${p1}")
            }
        })

    }

    //标签列表
    var tagList = mutableListOf<TagBean>()
    var tagName: String? = null

    /**
     * 获取专辑标签或者声音标签
     *
     *
     */
    private fun getTags(categoryId: String) {
        val map = HashMap<String, String>()
        //分类ID，指定分类，为0时表示热门分类
        categoryId?.let { map.put(DTransferConstants.CATEGORY_ID, it) }
        //指定查询的是专辑标签还是声音标签，0-专辑标签，1-声音标签
        map.put(DTransferConstants.TYPE, "0");
        CommonRequest.getTags(map, object : IDataCallBack<TagList> {

            override fun onError(p0: Int, p1: String?) {

            }

            override fun onSuccess(p0: TagList?) {
                tagList.clear()
                if (p0 != null && p0.tagList != null && p0.tagList.size > 0) {
                    //获取专辑
                    pageNo = 1
                    tagName = p0.tagList.get(0).tagName
                    getAlbumList(categoryId, tagName!!)

                    p0.tagList?.forEach {
                        if (p0?.tagList.indexOf(it) == 0) {
                            val bean = TagBean(true, it)
                            tagList?.add(bean)
                        } else {
                            val bean = TagBean(false, it)
                            tagList?.add(bean)
                        }

                    }
                    activityFindBinding?.rvTop?.layoutManager = LinearLayoutManager(
                        this@SearchActivity,
                        LinearLayoutManager.HORIZONTAL,
                        false
                    )


                    val tagAdapter = TagAdapter(R.layout.item_type_top, tagList)
                    tagAdapter?.apply {
                        setOnItemClickListener { adapter, view, position ->
                            tagList?.forEach {
                                if (tagList.indexOf(it) == position) {
                                    it.isSelect = true
                                    pageNo = 1
                                    tagName = it.tag.tagName
                                    getAlbumList(categoryId!!, tagName!!)

                                } else {
                                    it.isSelect = false
                                }

                            }
                            tagAdapter?.notifyDataSetChanged()
                            activityFindBinding?.rvTop?.scrollToPosition(position)
                        }
                    }
                    activityFindBinding?.rvTop?.adapter = tagAdapter
                }


            }

        })
    }

    var albumList = mutableListOf<Album>()

    /**
     * 根据分类和标签获取某个分类某个标签下的专辑列表
     * （最火/最新/最多播放）
     */
    private fun getAlbumList(categoryId: String, tagName: String) {
        val map = HashMap<String, String>()
        map[DTransferConstants.CATEGORY_ID] = categoryId
        map[DTransferConstants.TAG_NAME] = tagName
        map[DTransferConstants.CALC_DIMENSION] = "1"//计算维度，现支持最火（1），最新（2），经典或播放最多（3）
        //返回第几页，必须大于等于1，不填默认为1
        map.put(DTransferConstants.PAGE, pageNo.toString())
        //每页多少条，默认20，最多不超过200
        map.put(DTransferConstants.PAGE_SIZE, pageSize.toString())
        //付费
        map.put(DTransferConstants.CONTAINS_PAID, "false")
        CommonRequest.getAlbumList(map, object : IDataCallBack<AlbumList> {

            override fun onError(p0: Int, p1: String?) {
                activityFindBinding?.srHasData?.finishRefresh()
                activityFindBinding?.srHasData?.finishLoadMore()
                if (pageNo > 1) {
                    pageNo--
                }
                Toast.makeText(this@SearchActivity, "系统异常：${p1}", Toast.LENGTH_SHORT).show()
            }

            override fun onSuccess(p0: AlbumList?) {
                activityFindBinding?.srHasData?.finishRefresh()
                activityFindBinding?.srHasData?.finishLoadMore()
                if (p0 != null && p0.albums != null && p0.albums.size > 0) {
                    if (pageNo == 1) {
                        albumList.clear()
                    }
                    albumList.addAll(p0!!.albums)
                    val albumAdapter = AlbumAdapter(R.layout.item_album, albumList)
                    albumAdapter?.apply {
                        openLoadAnimation(BaseQuickAdapter.SCALEIN)//缩放
                        setOnItemClickListener { adapter, view, position ->
                            val item = adapter.getItem(position) as Album
                            val intent = Intent(this@SearchActivity, TracksActivity::class.java)
                            intent.putExtra("id", item.id.toString())
                            val bundle = Bundle()
                            bundle.putParcelable("album", item)
                            intent.putExtra("bundle", bundle)
                            startActivity(intent)
                        }

                    }

                    activityFindBinding?.rvRight?.adapter = albumAdapter
                } else {
                    if (pageNo > 1) {
                        pageNo--
                    }
                }
            }

        })
    }

}